package com.example.app.ui.screens

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LeadingIconTab
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.PullToRefreshState
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.app.extension.OnBottomReached
import com.example.app.ui.components.ArticleItem
import com.example.app.ui.components.NotificationContent
import com.example.app.ui.components.SwiperContent
import com.example.app.ui.components.TopAppBar
import com.example.app.ui.components.VideoItem
import com.example.app.ui.theme.Blue200
import com.example.app.ui.theme.Blue700
import com.example.app.viewmodel.ArticleViewModel
import com.example.app.viewmodel.MainViewModel
import com.example.app.viewmodel.VideoViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StudyScreen(
    vm: MainViewModel = viewModel(),
    articleViewModel: ArticleViewModel = viewModel(),
    videoViewModel: VideoViewModel = viewModel(),
    modifier: Modifier = Modifier,
    onNavigateToArticle: () -> Unit = {},
    onNavigateToStudyHistory: () -> Unit = {},
) {
    LaunchedEffect(Unit) {
        vm.categoryData()
        vm.swiperData()
        articleViewModel.articleListData()
    }
    val coroutineScope = rememberCoroutineScope()
    val lazyListState = rememberLazyListState()
    lazyListState.OnBottomReached(buffer = 3) {
        Log.i("===", "OnBottomReached")
        coroutineScope.launch {
            articleViewModel.loadMore()
        }
    }

    Column(modifier = modifier) {
        //标题栏
        TopAppBar(
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        listOf(
                            Blue700, Blue200
                        )
                    )
                )
                .padding(horizontal = 8.dp)
        ) {
            //搜索按钮
            Surface(
                modifier = Modifier
                    .weight(1f)
                    .clip(RoundedCornerShape(16.dp)),
                color = Color(0x33FFFFFF)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(
                        horizontal = 8.dp, vertical = 4.dp
                    )
                ) {
                    Icon(
                        imageVector = Icons.Filled.Search,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(14.dp)
                    )
                    Text(
                        text = "搜索感兴趣的咨询和课程",
                        color = Color.White,
                        fontSize = 12.sp,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            Spacer(modifier = Modifier.width(18.dp))
            //学习进度
            Text(text = "学习\n进度",
                fontSize = 10.sp,
                color = Color.White,
                modifier = Modifier.clickable {
                    onNavigateToStudyHistory()
                })
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = "26%", fontSize = 12.sp, color = Color.White)
            Spacer(modifier = Modifier.width(8.dp))
            Icon(
                imageVector = Icons.Default.Notifications,
                contentDescription = null,
                tint = Color.White
            )
        }
        //分类标签
        TabRow(selectedTabIndex = vm.categoryIndex,
            containerColor = Color(0x22149EE7),
            indicator = { tabPositions ->
                CustomTabIndicator(tabPositions[vm.categoryIndex])
            }) {
            vm.categories.forEachIndexed { index, category ->
                Tab(selected = vm.categoryIndex == index,
                    selectedContentColor = Color(0xFF149EE7),
                    unselectedContentColor = Color(0xFF666666),
                    onClick = { vm.updateCategoryIndex(index) }) {
                    Text(
                        text = category.title,
                        fontSize = 14.sp,
                        modifier = Modifier.padding(vertical = 8.dp)
                    )
                }
            }
        }
        TabRow(selectedTabIndex = vm.typeIndex,
//            containerColor = Color(0x22149EE7),
            indicator = {}, divider = {}) {
            vm.types.forEachIndexed { index, s ->
                LeadingIconTab(selected = vm.typeIndex == index,
                    selectedContentColor = Color(0xFF149EE7),
                    unselectedContentColor = Color(0xFF666666),
                    onClick = { vm.updateTypeIndex(index) },
                    text = {
                        Text(
                            text = s.title, modifier = Modifier.padding(8.dp), fontSize = 16.sp
                        )
                    },
                    icon = {
                        Icon(imageVector = s.icon, contentDescription = null)
                    })

            }
        }
        val pullToRefreshState: PullToRefreshState = rememberPullToRefreshState()
        if (pullToRefreshState.isRefreshing) {
            LaunchedEffect(true) {
                articleViewModel.refresh()
            }
        }
        Box(Modifier.nestedScroll(pullToRefreshState.nestedScrollConnection)) {
            PullToRefreshContainer(
                state = pullToRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
//                .pullRefreshIndicatorTransform(pullToRefreshState)
            )
//            if (pullToRefreshState.isRefreshing) {
//                CircularProgressIndicator()
//            } else {
//                CircularProgressIndicator(progress = { pullToRefreshState.progress })
//            }
            LazyColumn(state = lazyListState) {
                //轮播图
                item { SwiperContent(vm) }
                //通知公告
                item { NotificationContent(vm) }
                if (vm.typeIndex == 0) {
                    //新闻列表
                    items(articleViewModel.list.size) { index ->
                        ArticleItem(articleViewModel.list[index],
                            modifier = Modifier.clickable { onNavigateToArticle.invoke() })
                    }
                } else {
                    //视频列表
                    items(videoViewModel.list.size) { index ->
                        VideoItem(videoViewModel.list[index])
                    }
                }
            }
        }
    }
}


@Composable
fun CustomTabIndicator(tabPosition: TabPosition) {
    Box(
        modifier = Modifier
            .tabIndicatorOffset(tabPosition)
//            .width(0.dp)
            .height(3.dp)
            .clip(RoundedCornerShape(2.dp))
            .background(Color(0xFF149EE7))
    )
}

@Preview(showSystemUi = true)
@Composable
fun StudyScreenPreview() {
    StudyScreen()
}


